package com.wchat.configurer;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Component
@ConfigurationProperties(prefix = "rediss")
@Data
public class RedisPoolConfig {

    /**Jedis连接池**/
    private static JedisPool pool;

    /** 最大连接数**/
    @Value("${max.toal}")
    private static Integer maxTotal = 200;

    /**在jedispool中最大的idle（空闲状态）的jedis连接数**/
    @Value("${max-idle}")
    private static Integer maxIdle = 100;

    /**在jedispool中最小的idle（空闲状态）的jedis连接数**/
    @Value("${min-idle}")
    private static Integer minIdle = 2;

    /**连接redis的ip地址**/
    @Value("${redis-ip}")
    private static String redisIp = "127.0.0.1";

    /**连接redis的端口号**/
    @Value("${redis-port}")
    private static Integer redisPort = 6380;

    /**在borrow一个jedis实例时候，是否需要进行验证 如果为true**/
    @Value("${test-borrow}")
    private static Boolean testOnBorrow = true;

    /**在return一个jedis实例的时候是需要验证**/
    @Value("${test-return}")
    private static Boolean testOnReturn = true;

    private static void initPool(){

        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(maxTotal);
        config.setMaxIdle(maxIdle);
        config.setMinIdle(minIdle);
        config.setTestOnBorrow(testOnBorrow);
        config.setTestOnReturn(testOnReturn);
        config.setBlockWhenExhausted(true);//  连接耗尽时候 是否阻塞。
        pool = new JedisPool(config,redisIp,redisPort,1000*10);
    }

    /**
     * 静态初始块  初始化pool
     */
    static{
        System.out.println(maxTotal);
        initPool();
    }

    public static Jedis getJedis(){
        return pool.getResource();
    }

    public static void returnResource(Jedis jedis){
        pool.returnResource(jedis);
    }

    public static void returnBrokenResource(Jedis jedis){
        pool.returnBrokenResource(jedis);
    }

    public static void main(String[] args) {
        Jedis jedis = pool.getResource();
        jedis.set("you","you"); //  测试方法设置set get
        returnResource(jedis);
        Integer code = 1;
        String newCode = "1";
        System.out.println(code.equals(newCode));
        pool.destroy();  //  临时调用销毁函数  销毁连接池在我会给你的所有连接

        System.out.println("程序结束");

    }



}
